package com.example.demo.user.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.user.entity.UServiceUser;
import com.example.demo.user.service.UServiceUserService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.util.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.user.service.IUServiceUserRelationService;
import com.example.demo.user.entity.UServiceUserRelation;

import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 账号服务人员关系表; 前端控制器
 * </p>
 *
 * @author tao
 * @since 2025-04-03
 */
@RestController
@RequestMapping("/uServiceUserRelation")
    public class UServiceUserRelationController {

    @Autowired
    private IUServiceUserRelationService uServiceUserRelationService;

    @Autowired
    private UServiceUserService uServiceUserService;

    /**
    * 获取相关列表
     * @param current
     * @param size
     * @return
    */
    @GetMapping("/getUServiceUserRelationList")
    public Result<?> getUServiceUserRelationList(@RequestParam(value = "current", required = false, defaultValue = "1")Integer current,
                                            @RequestParam(value = "size", required = false, defaultValue = "10")Integer size,
                                            UServiceUserRelation uServiceUserRelation){

        Page<UServiceUserRelation> page = new Page<>(current,size);
        QueryWrapper<UServiceUserRelation> queryWrapper=new QueryWrapper<>(uServiceUserRelation);
        queryWrapper.select("u_service_user_relation.*,(select name from u_service_user where u_service_user.id = u_service_user_relation.classification_id) as accountName");
        queryWrapper.orderByDesc("id");

        return Result.ok(uServiceUserRelationService.page(page,queryWrapper));
    }

    /**
         * 根据ID查询信息
         */
    @GetMapping("/getUServiceUserRelationById")
    public Result<?> getUServiceUserRelationById(Integer id){
        return Result.ok(uServiceUserRelationService.getById(id));
    }

    /**
         * 修改
         */
    @PutMapping("/updateUServiceUserRelation")
    @Transactional
    public Result<?> updateUServiceUserRelation(@RequestBody UServiceUserRelation uServiceUserRelation){
        return Result.ok(uServiceUserRelationService.updateById(uServiceUserRelation));
    }

    /**
         * 新增
         */
    @PostMapping("/addUServiceUserRelation")
    public Result<?> addUServiceUserRelation(@RequestBody UServiceUserRelation uServiceUserRelation){
        return Result.ok(uServiceUserRelationService.save(uServiceUserRelation));
    }

    /**
         * 删除
         */
    @DeleteMapping("/deleteUServiceUserRelationById")
    @Transactional
    public Result<?> deleteUServiceUserRelation(UServiceUserRelation uServiceUserRelation){
        QueryWrapper<UServiceUserRelation> wrapper = new QueryWrapper<>(uServiceUserRelation);
        return Result.ok(uServiceUserRelationService.remove(wrapper));
    }

    /**
     * pc端口账号管理添加运营人员时获取未选相关人员列表
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getAllUServiceUserList")
    public Result<?> getAllUServiceUserList(@RequestParam(value = "current", required = false, defaultValue = "1")Integer current,
                                                 @RequestParam(value = "size", required = false, defaultValue = "5")Integer size,
                                                 UServiceUserRelation uServiceUserRelation){
        Page<UServiceUser> page = new Page<>(current,size);
        QueryWrapper<UServiceUser> queryWrapper = new QueryWrapper<>();

        QueryWrapper<UServiceUserRelation> wrapper = new QueryWrapper<>(uServiceUserRelation);
        List<UServiceUserRelation> list = uServiceUserRelationService.list(wrapper);
        if(!CollectionUtils.isEmpty(list)){
            List<Integer> selectedIds = new ArrayList<>();
            for(UServiceUserRelation u:list){
                selectedIds.add(u.getUid());
            }
            queryWrapper.notIn("id",selectedIds);
        }
        queryWrapper.orderByDesc("id");

        return Result.ok(uServiceUserService.page(page,queryWrapper));
    }

    /**
     * pc端口账号管理添加运营人员时获取已选择相关人员列表
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/getSelectedUServiceUserList")
    public Result<?> getSelectedUServiceUserList(@RequestParam(value = "current", required = false, defaultValue = "1")Integer current,
                                            @RequestParam(value = "size", required = false, defaultValue = "5")Integer size,
                                            UServiceUserRelation uServiceUserRelation){
        Page<UServiceUser> page = new Page<>(current,size);
        QueryWrapper<UServiceUser> queryWrapper = new QueryWrapper<>();

        QueryWrapper<UServiceUserRelation> wrapper = new QueryWrapper<>(uServiceUserRelation);
        List<UServiceUserRelation> list = uServiceUserRelationService.list(wrapper);
        if(!CollectionUtils.isEmpty(list)){
            List<Integer> selectedIds = new ArrayList<>();
            for(UServiceUserRelation u:list){
                selectedIds.add(u.getUid());
            }
            queryWrapper.in("id",selectedIds);
            queryWrapper.orderByDesc("id");
        }else{
            queryWrapper.lt("id", 0);
        }

        return Result.ok(uServiceUserService.page(page,queryWrapper));
    }

    /**
     * pc端口账号添加运营人员
     * @return
     */
    @PostMapping("/addRelation")
    public Result<?> addRelation(@RequestBody UServiceUserRelation uServiceUserRelation){
        List<Integer> idArray = Arrays.stream(uServiceUserRelation.getIds().split(","))
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        QueryWrapper<UServiceUserRelation> wrapper = new QueryWrapper<>(uServiceUserRelation);
        List<UServiceUserRelation> list = uServiceUserRelationService.list(wrapper);

        Map<Integer, UServiceUserRelation> idToRelationMap = new HashMap<>();
        for (UServiceUserRelation relation : list) {
            idToRelationMap.put(relation.getUid(), relation);
        }

        for(Integer id : idArray){
            if (!idToRelationMap.containsKey(id)) {
                UServiceUserRelation userRelation = new UServiceUserRelation();
                userRelation.setRelation(uServiceUserRelation.getRelation());
                userRelation.setUid(id);
                userRelation.setClassificationId(uServiceUserRelation.getClassificationId());
                uServiceUserRelationService.save(userRelation);
            }
        }

        // 删除逻辑
        for (Map.Entry<Integer, UServiceUserRelation> entry : idToRelationMap.entrySet()) {
            if (!idArray.contains(entry.getKey())) {
                uServiceUserRelationService.removeById(entry.getValue().getId());
            }
        }

        return Result.ok();
    }

}